//每次选中数据库后赋予该集合
var tempResult = {};

var tableNames = new Array();
layui.use(['form', 'layedit', 'laydate', 'jquery', 'table'], function () {

    var form = layui.form
        , layer = layui.layer
        , layedit = layui.layedit
        , laydate = layui.laydate;

    var table = layui.table;

    //执行渲染
    table.render({
        elem: '#table-demo' //指定原始表格元素选择器（推荐id选择器）
        , url: '/getTableNames'
        , height: 310 //容器高度
        , id: 'idTest'
        , cols: [[
            {type: 'checkbox', width: '5%'}
            , {field: 'tableName', width: '35%', title: '表名称', sort: true}
            , {field: 'tableType', width: '20%', title: '数据库引擎'}
            , {field: 'tableType', width: '20%', title: '字符集'}
            , {field: 'tableDes', width: '20%', title: '操作', align: 'center', toolbar: '#barDemo'}
        ]]
        , done: function (res, curr, count) {
            layer.closeAll();
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            tempResult = res;
            console.log(res);
            //得到当前页码
            console.log(curr);
            //得到数据总量
            console.log(count);
        }
    });

    //监听工具条
    table.on('tool(table-demo)', function (obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            layer.msg('编辑行：<br>' + JSON.stringify(data) + data.tableName);
            $('#hid_table_name').val(data.tableName);
            getMsg();
        }
    });
    //监听复选框选择
    table.on('checkbox(table-demo)', function (obj) {
        tableNames = new Array();
        var checkStatus = table.checkStatus('idTest'); //test即为基础参数id对应的值
        for (var i = 0; i < checkStatus.data.length; i++) {
            tableNames.push(checkStatus.data[i].tableName);
        }
        $('#hid_table_name').val(tableNames);
    });

    var $ = jQuery = layui.$;

    function getMsg() {
        $.post('/generateFile', getFormData(), function (result) {
            if (result.code == 0) {
                layer.msg(result.msg);
            } else {
                layer.msg("文件生成失败");
            }

        })
    }

    //生成选中的表
    $(function () {
        $('#gen').click(function () {
            getMsg();
        });
    });


    //自定义验证规则
    form.verify({
        url: function (value) {
            if (value.length < 5) {
                return '数据库连接至少得5个字符啊';
            }
        }
        , pass: [/(.+){6,12}$/, '密码必须6到12位']
        , content: function (value) {
            layedit.sync(editIndex);
        }
    });

    //监听提交
    form.on('submit(demo1)', function (data) {
        //console.log(data.field); //当前容器的全部表单字段，名值对形式：{name: value}
        return false;
    });


    //监听数据库改变
    form.on('select(sel-db)', function (data) {
        $('#hid_db_name').val(data.value);
        var index = layer.load(1, {
            shade: [0.6, '#393D49'] //0.1透明度的白色背景
        });
        table.reload('idTest', {
            where: getFormData()
        });
    });

    //表单初始赋值
    form.val('db', {
        "url": "127.0.0.1"
        , "port": "3306"
        , "username": "root"
        , "password": "123456"
    });
    //表单初始赋值
    form.val('xm', {
        "rootPath": "com.lkx"
        , "servicePath": "service"
        , "daoPath": "dao"
        , "mapperPath": "mapper"
        , "entityPath": "entity"
        , "webPath": "web"
        , "author": "素剑步青尘"
    })

    $('#demo1').click(function (data) {
        var index = layer.load(1, {
            shade: [0.6, '#393D49'] //0.1透明度的白色背景
        });
        $.ajax({
            url: $("#myform").attr("action"),
            type: $("#myform").attr("method"),
            data: getFormData(),
            success: function (data) {
                layer.closeAll();
                if (data.code == 200) {
                    $('#link-msg').html(data.msg);
                    dblist(data.list);
                } else {
                    $('#link-msg').html(data.msg);
                }
                return false;
            },
            error: function (data) {
                layer.closeAll();
                $('#link-msg').html('连接失败');
                layer.msg('连接失败');
            }
        });
    });

    /**
     * 释放数据库链接
     */
    $('#closedb').click(function (data) {
        var index = layer.load(1, {
            shade: [0.6, '#393D49'] //0.1透明度的白色背景
        });
        var params = {
            url: $('#url').val(),
            username: $('#username').val(),
            password: $('#password').val(),
            port: $('#port').val()
        }
        $.ajax({
            url: "/closeDB",
            type: $("#myform").attr("method"),
            data: params,
            success: function (data) {
                layer.closeAll();
                if (data.code == 200) {
                    $('#link-msg').html(data.msg);
                    dblist(data.list);
                } else {
                    $('#link-msg').html(data.msg);
                }
                return false;
            }
        });
    });

    function dblist(data) {
        var selDom = $("#sel-db");
        selDom.html('');
        for (var i = 0; i < data.length; i++) {
            console.log(data[i]);
            selDom.append("<option value='" + data[i] + "'>" + data[i] + "</option>");//添加option
        }
        form.render('select');
    }


    function getFormData() {
        var postData = $("#myform").serialize();
        var tmpDic = {};
        for (var i in postData.split("&")) {
            var row = postData.split("&")[i];
            tmpDic[row.split("=")[0]] = decodeURIComponent(row.split("=")[1]);
        }

        var postData = $("#xm").serialize();
        for (var i in postData.split("&")) {
            var row = postData.split("&")[i];
            tmpDic[row.split("=")[0]] = decodeURIComponent(row.split("=")[1]);
        }
        return tmpDic;
    }

    //当键盘按键弹起时自动进行搜索：
    $('#search_table_name').keyup(function () {
        // 1.获得搜索框的值；
        // 2.判断如果有值。layer.msg()
        // 3.定义延时函数，0.8s后刷新表格，并传递参数；
        // 4.关闭layer.msg()
        var keyWord = $('#search_table_name').val();
        $('#hid_key_word').val(keyWord);
        if (keyWord != '') {
            setTimeout(function () {
                var index = layer.load(1, {
                    shade: [0.1, '#393D49'] //0.1透明度的白色背景
                });
                table.reload('idTest', {
                    where: getFormData()
                });
                layer.closeAll();
            }, 200);
        } else {
            table.reload('idTest', {
                where: getFormData()
            });
        }
    });


});


